<?php

class IssueController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','admin','update','create','delete',
						'assign','resolve','assigneditor','assignresolve','check','edit',
						'setassign','setassigneditor','setassigneditoranswer','setresolve',
						'setcheck','setresolvesubmit','seteditsubmit','setedit','sendmail'),
				'users'=>array('@'),
			),	
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Issue']))
		{
			$model->attributes=$_POST['Issue'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	/*
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Issue');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}*/

	
	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('index',array(
			'model'=>$model,
		));
	}
	
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Issue::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='issue-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	/**
	 * Assign to resolver
	 * @author khatv
	 */
	public function actionAssign() {
	  $ID = isset($_GET['id'])?$_GET['id']:'';
		$model=new Issue('assign');
		
		$this->render('assign',array(
			'model'=>$model, 'ID'=>$ID
		));
	}
	
	public function actionSetAssign() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $resolverID = $_POST['resolverID'];
		  $status = $_POST['status']; 
      $log ="";
      $answer = Answer::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number,'resolver'=>$resolverID));
      
      if(empty($answer)) {
        $answer = new Answer();
        $answer->issueID = $issueID;
        $answer->thread_number = $thread_number;      
      }
      // set status for thread is assigned
      if($status=="assign") {      	
        $answer->resolve_status = 31;
        $log =Yii::app()->user->id . " assign " .$resolverID. "to resolve question ". $thread_number. " of issue " .$issueID;
      } 
      else if($status=="confirm") {      	
      	$answer->resolve_status  = 37;
      	$log =Yii::app()->user->id . " confirm " .$resolverID. "to resolve question ". $thread_number. " of issue " .$issueID;
      }
      else if($status=="reassign"){      	
      	$answer->resolve_status  = 36;
      	 $log =Yii::app()->user->id . " re-assign " .$resolverID. "to resolve question ". $thread_number. " of issue " .$issueID;
      }
      else {
      	// do some thing
      }
      
      $answer->resolver = $resolverID;     
      $answer->createddate = time();
      $answer->save(false);
      
      // update resolver status.
			$user_status = UserStatus::model()->findByAttributes(array('userID'=>$resolverID));
			if(!empty($user_status))
			{
				$user_status->statusID = 3;
				$user_status->update(false);
			}        
			
			// update or insert assignment record
		 	Assignment::model()->updateAssignment($resolverID,$answer->ID,$log);		
    	echo "success";
		}
	}
	public function actionSendMail()
	{
		$to ="vankha89@gmail.com";
		$subject="test mail from php";
		$body="the first test mail";
		$from_email ="local1@example.gbt.vn";
		$from_name="kha tran";
		
		
		
		$headers  = "MIME-Version: 1.0 \n" ;
		$headers .= "From: " .
		       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
		       "<".$from_email."> \n";
		$headers .= "Reply-To: " .
		       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
		       "<".$from_email."> \n";
		 
		    
		$headers .= "Content-Type: text/plain;charset=ISO-2022-JP \n";
		
		    
		/* Convert body to same encoding as stated 
		in Content-Type header above */
		    
		$body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");
		    
		/* Mail, optional paramiters. */
		$sendmail_params  = "-f$from_email";
		    
		mb_language("ja");
		$subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
		$subject = mb_encode_mimeheader($subject);
		
		$result = mail($to, $subject, $body, $headers, $sendmail_params);
		       
		return $result;
	}
	/**
	 * Assign to editor
	 * @author khatv
	 */
	public function actionAssignEditor() {
		$ID = isset($_GET['id'])?$_GET['id']:'';
	  $model=new Issue('assign');

		$this->render('assigneditor',array(
			'model'=>$model, 'ID'=>$ID
		));
	}
	
	public function actionSetAssignEditor() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $ediorID = $_POST['ediorID'];
		  $status = $_POST['status']; 
		  
      $question = Question::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));
      if(empty($question)) {
        $question = new Question();
        $question->issueID = $issueID;
        $question->thread_number = $thread_number;  
        $question->save(false)    ;
      }	
      		
      // assign to edit question
      if($status=="assign")
      {
        $question->status = 41;
      }
			else if($status=="confirm")
      {
        $question->confirmStatus();
      }
      else if($status=="reassign")
      {
        $question->status = 43;
        $question->editor = $ediorID;
         // update resolver status.
				$user_status = UserStatus::model()->findByAttributes(array('userID'=>$ediorID));
				if(!empty($user_status))
				{
					$user_status->statusID = 3;
					$user_status->update();					
				}
				Assignment::model()->updateAssignment($ediorID,$question->ID,'assign editing question');
      }
      
      $question->modifieddate = time();
      $question->update(); 
			
      echo "success";
		}
	}
/**
	 * Assign to editor 
	 * @author khatv
	 */
	public function actionAssignResolve() {
		$ID = isset($_GET['id'])?$_GET['id']:'';
	  $model=new Issue('assign');

		$this->render('assignresolve',array(
			'model'=>$model, 'ID'=>$ID
		));
	}
	public function actionSetAssignResolve() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $resolverID = $_POST['resolverID'];
		  $status = $_POST['status']; 
		  $answerID =$_POST['answerID'];
		  
      $thread = Thread::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));
      if(empty($thread)) {
        $thread = new Thread();
        $thread->issueID = $issueID;
        $thread->thread_number = $thread_number;      
      }			
      if($status=="ok") {
        $thread->status = 31;
      }
      else {
        $thread->status = 30;
      }
        $thread->editor = $resolverID; 
        $thread->answerID =  $answerID;   
        $thread->assigneddate = time();
        $thread->save(false);
        
        // update resolver status.
				$user_status = UserStatus::model()->findByAttributes(array('userID'=>$resolverID));
				if(!empty($user_status))
				{
					$user_status->statusID = 3;
					$user_status->update();
				}      
        
				Assignment::model()->updateAssignment($resolverID,$thread->ID,'assign resolve');
				//update version
				$version = Answer::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));
				if(!empty($version)){
					$version->resolve_version = $version->resolve_version+1;
					$version->edit_version = $version->edit_version+1;
					$version->update();
				}
        echo "success";
		}
	}
	
	/*
	 * Resolver submit the answer.
	 */
	public function actionSubmitAnswer()
	{
			
	}
	
	/**
	 * Resolve
	 * @author khatv
	 */
	public function actionResolve() {
		$ID = isset($_GET['id'])?$_GET['id']:'';
	  $model=new Issue('resolve');
		
		$this->render('resolve',array(
			'model'=>$model, 'ID'=>$ID
		));
	}
	
	public function actionSetResolve() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $resolverID = $_POST['resolverID'];
		  $status = $_POST['status']; 
		  
      $thread = Answer::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));

      if(empty($thread)) {
        $thread = new Answer();
        $thread->issueID = $issueID;
        $thread->thread_number = $thread_number;      
      }			
      if($status=="ok") {
        $thread->resolve_status = 31;
      }
      else {
        $thread->status = 30;
      }
        $thread->resolve_status = $resolverID;     
        $thread->createddate = time();
        $thread->save(false);
        
        // update resolver status.
				$user_status = UserStatus::model()->findByAttributes(array('userID'=>$resolverID));
				if(!empty($user_status))
				{
					$user_status->statusID = 3;
					$user_status->update();
				} 
				
				echo "success";
		}
	}
	public function actionSetResolveSubmit() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
			
				//data: {issueID: issueID, resolverID: resolverID, answerID: answerID},
				$issueID = $_POST['issueID'];
		  	$answerID = $_POST['answerID']; 
				$answer = Answer::model()->findByAttributes(array('issueID'=>$issueID,'ID'=>$answerID));
			
				if(!empty($answer)) {
        	$answer->resolve_status = 35;   
        	$answer->update();
       	echo "success";
    	  }			
    	}
	}
	
	public function actionSetEditSubmit() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
			
				//data: {issueID: issueID, resolverID: resolverID, answerID: answerID},
				$issueID = $_POST['issueID'];
		  	$answerID = $_POST['answerID']; 
				$answer = Answer::model()->findByAttributes(array('issueID'=>$issueID,'ID'=>$answerID));
			
				if(!empty($answer)) {
      	//	$answer->edit_status = 44;   
        	$answer->update();
       	echo "success";
    	  }			
    	}
	}
	
	
	/**
	 * Resolve
	 * @author khatv
	 */
	public function actionEdit() {
		$ID = isset($_GET['id'])?$_GET['id']:'';
	  $model=new Issue('assign');

		$this->render('edit',array(
			'model'=>$model, 'ID'=>$ID
		));	
		
	}
	
	public function actionSetEdit() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $editID = $_POST['resolverID'];
		  $status = $_POST['status']; 
		  
      $thread = Answer::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));

      if(empty($thread)) {
        $thread = new Answer();
        $thread->issueID = $issueID;
        $thread->thread_number = $thread_number;      
      }			     
      $thread->save(false);        
     
        
        echo "success";
		}
	}
	
	/**
	 * Check
	 * @author khatv
	 */
	public function actionCheck() {
		$ID = isset($_GET['id'])?$_GET['id']:'';
	  $model=new Issue('assign');

		$this->render('check',array(
			'model'=>$model, 'ID'=>$ID
		));
	}
	
	public function actionSetCheck() {
		if(Yii::app()->request->isAjaxRequest) { //chi chap nhan request cua ajax thoi
		  $issueID = $_POST['issueID'];
		  $thread_number = $_POST['num'];
		  $resolverID = $_POST['resolverID'];
		  $status = $_POST['status']; 
		  
      $answer = Answer::model()->findByAttributes(array('issueID'=>$issueID,'thread_number'=>$thread_number));
      if(empty($answer)) {
        $answer = new Answer();
        $answer->issueID = $issueID;
        $answer->thread_number = $thread_number;
        $answer->save(false);
      }		
      	
      // confirm 
      if($status=="confirm")
      {    	      	     	
        $answer->confirmStatus('resolve');
      }
      else if($status=="reassign")
      {
      	// re-assign to resolver
        $answer->resolve_status = 36;
        $answer->resolver = $resolverID;        
         // update resolver status.
				$user_status = UserStatus::model()->findByAttributes(array('userID'=>$resolverID));
				if(!empty($user_status))
				{
					$user_status->statusID = 3;
					$user_status->update();
				}
				// if status is ok, update assignment result to 1, esle add new re-assign asignment
        Assignment::model()->updateAssignment($resolverID,$thread->ID,'re-assign');				
      }      
       
      $answer->modifieddate =time();
      $answer->update();
       
        echo "success";
		}
	}
}